<template>
  <div class="userChat">
    <van-nav-bar
      class="page-nav-bar"
      title="小智同学"
      left-arrow
      @click-left="$router.back()"
    />

    <van-cell-group class="messageList">
      <van-cell title="单元格" />
      <van-cell title="单元格" />
    </van-cell-group>

    <van-cell-group class="sendMessage">
      <van-field v-model="message" placeholder="请输入消息" :border="false" />
      <van-button type="primary" size="small" @click="onSend">发送</van-button>
    </van-cell-group>
  </div>
</template>

<script>
import io from "socket.io-client";
export default {
  name: "userChat",
  data() {
    return {
      message: "",
      socket: null
    };
  },
  created() {
    //   建立连接
    const socket = io("http://ttapi.research.itcast.cn");
    this.socket = socket;
    socket.on("connect", () => {
      console.log("连接成功");
    });

    socket.on("disconnect", () => {
      console.log("断开连接");
    });
    // 监听message事件，接收服务端消息
    socket.on("message", data => {
      //   console.log(data);
      // 把对方给我的消息也放到数组中
      this.messages.push(data);
    });
  },
  methods: {
    onSend() {
      const data = {
        msg: this.message,
        timestamp: Date.now()
      };
      this.socket.emit("message", data);

      //   把用户发出去的消息存储到数组中
      this.messages.push(data);
    }
  }
};
</script>
<style scoped lang="less">
.sendMessage {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  padding: 0 14px;
  align-items: center;
}
.messageList {
  position: fixed;
  top: 46px;
  left: 0;
  right: 0;
  bottom: 44px;
  overflow-y: auto;
}
</style>
